package com.itheima.nio.tomcat.parse;

import com.itheima.nio.tomcat.exception.IsNotImplementsHttpServletException;
import com.itheima.nio.tomcat.inter.HttpServlet;
import com.itheima.nio.tomcat.inter.ParseServletConfig;
import com.itheima.nio.tomcat.inter.ServletConcurrentHashMap;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.List;

public class XmlParseServletConfig implements ParseServletConfig {

    public static final String WEB_APP_PATH = "itheima-nio-tomcat\\webapp/WEB-INF/web.xml";

    @Override
    public void parse() {
        SAXReader saxReader = new SAXReader();
        try {
            Document document = saxReader.read(new FileInputStream(WEB_APP_PATH));
            Element rootElement = document.getRootElement();
            HashMap<String, String> hashMap = new HashMap<>();
            List<Element> servletInfos = rootElement.elements("servlet");
            for (Element servlet : servletInfos){
                String servletName = servlet.element("servlet-name").getText();
                String servletClassName = servlet.element("servlet-class").getText();
                hashMap.put(servletName, servletClassName);
            }
            List<Element> servletMappingInfos = rootElement.elements("servlet-mapping");
            for (Element servletMappingInfo : servletMappingInfos){
                String servletName = servletMappingInfo.element("servlet-name").getText();
                String urlPattern = servletMappingInfo.element("url-pattern").getText();
                String servletClassName = hashMap.get(servletName);
                Class<?> servletClass = Class.forName(servletClassName);
                boolean flag = false;
                Class<?>[] interfaces = servletClass.getInterfaces();
                for (Class cla : interfaces){
                    if (cla == HttpServlet.class){
                        flag = true;
                        break;
                    }
                }
                if (flag){
                    HttpServlet httpServlet = (HttpServlet) servletClass.newInstance();
                    ServletConcurrentHashMap.concurrentHashMap.put(urlPattern, httpServlet);
                } else {
                    try{
                        throw new IsNotImplementsHttpServletException(servletClass.getName() + "is not implements HttpServlet interface");
                    } catch (IsNotImplementsHttpServletException e){
                        e.printStackTrace();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
